#include "mytablewidget.h"

MyTableWidget::MyTableWidget(QWidget* parent) : QTableWidget(parent) {}

void MyTableWidget::resizeEvent(QResizeEvent* event){

    qDebug() << "触发表格大小调整事件";
    // 调用 resizeColumnsToContents 以确保每个单元格都能完全显示
    this->resizeColumnsToContents();  // 根据内容自动调整列宽

    QScrollBar* verticalScrollBar = this->verticalScrollBar();
    // 获取表格的可视宽度（考虑滚动条等因素后的实际可用宽度）
    int availableWidth = verticalScrollBar && verticalScrollBar->isVisible()?viewport()->width():this->width();

    // 计算所有列的总宽度
    int totalColumnWidth = 0;
    for (int i = 0; i < this->columnCount(); ++i) {
        totalColumnWidth += this->columnWidth(i);
    }

    // 如果列的总宽度小于可视宽度，才进行宽度分配调整
    if (totalColumnWidth < availableWidth) {
        int remainingWidth = availableWidth - totalColumnWidth;

        // 假设将剩余宽度平均分配给每一列
        int extraWidthPerColumn = remainingWidth / this->columnCount();

        // 更新每列的宽度
        for (int i = 0; i < this->columnCount(); ++i) {
            int currentWidth = this->columnWidth(i);
            this->setColumnWidth(i, currentWidth + extraWidthPerColumn);
        }
    }
    // 调用基类的 resizeEvent 以确保标准的调整行为
    QTableWidget::resizeEvent(event);
}

/*void MyTableWidget::mousePressEvent(QMouseEvent* event)
{
    QHeaderView* headerView = horizontalHeader();
    for (int i = 0; i < headerView->count(); ++i)
    {
        int xPos = headerView->sectionViewportPosition(i);
        int sectionWidth = headerView->sectionSize(i);
        QRect sectionRect(xPos, 0, sectionWidth, headerView->height());
        // 判断鼠标位置是否在列头的调整宽度区域（右侧边界附近，这里可根据实际调整合适范围）
        if (event->pos().x() >= sectionRect.right() - 5 && event->pos().x() <= sectionRect.right() + 5)
        {
            event->ignore();
            return;
        }
    }
    QTableWidget::mousePressEvent(event);
}*/
